package com.bdk.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.bdk.conmon.ResultCode;
import com.bdk.conmon.ResultEntity;
import com.bdk.conmon.SystemCons;
import com.bdk.dao.UserMapper;
import com.bdk.mapper.User;
import com.bdk.model.PageJson;
import com.bdk.model.UserVO;
import com.bdk.service.IUserService;
import com.bdk.utill.JSONUtils;
import com.bdk.utill.StringHelper;

/**
 * 用户相关实现 ClassName: UserServiceImpl
 * 
 * @Description:
 * @author ChenQuan
 * @date 2017年5月4日下午1:57:23
 */
@Service("userService")
public class UserServiceImpl implements IUserService {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private UserMapper userDao;

	
	//7、修改用户
	@Override
	public String update(UserVO user,HttpServletRequest request) {
		  User u=new User();
		  PageJson p=new PageJson();
		  BeanUtils.copyProperties(user, u);
		//校验用户是否已登录
		  if(SystemCons.checkLoging(request)){
			  try{
				  User loginUser = SystemCons.getUser(request);
				  user.setCompany(loginUser.getCompany());
				  userDao.update(u);		  
				  logger.info("修改用户信息成功");
				  p.setCode(ResultCode.OK.getValue());
				  p.setMsg(ResultCode.OK.getName());
				  return JSON.toJSONString(p);
			  }catch(Exception e){
				    p.setCode(ResultCode.ERRO.getValue());
					p.setMsg(ResultCode.ERRO.getName());
					logger.info("异常信息："+e.getMessage());
					return JSON.toJSONString(p);
			  }
		  }else{
			    p.setCode(ResultCode.NOTLOGIN.getValue());
				p.setMsg(ResultCode.NOTLOGIN.getName());
				logger.info("新增用户  -- 用户未登录");
				return JSON.toJSONString(p);
		  }
		
		
	}
	
	public String addUserJson(UserVO u,HttpServletRequest request){
		  User user=new User();
		  PageJson p=new PageJson();
		  BeanUtils.copyProperties(u, user);
		  user.setId(UUID.randomUUID().toString());//生成不重复的UUID
		  //校验用户是否已登录
		  if(SystemCons.checkLoging(request)){
			  try{
			      if(StringHelper.isEmpty(u.getPassword()) || StringHelper.isEmpty(u.getRepassword())){
						p.setCode(ResultCode.PARAMERR.getValue());
						p.setMsg(ResultCode.PARAMERR.getName());
						return JSON.toJSONString(p);
			      }
			      if(null != userDao.queryUserList(user.getName(), 1, 1) && userDao.queryUserName(u.getName())>0)
			      {
			    	    p.setCode(ResultCode.USERNAMEISUSED.getValue());
						p.setMsg(ResultCode.USERNAMEISUSED.getName());
						return JSON.toJSONString(p);
			      }
			      //校验两次密码是否一致
			      if(!u.getPassword().equals(u.getRepassword())){
						p.setCode(ResultCode.NOTEQUALPWD.getValue());
						p.setMsg(ResultCode.NOTEQUALPWD.getName());
						return JSON.toJSONString(p);
			      }
				  
				  user.setPassword(StringHelper.encodPayPwd(user.getPassword()));
				  //设置添加用户默认所属公司
				  User loginUser = SystemCons.getUser(request);
				  user.setCompany(loginUser.getCompany());
				  userDao.insertSelective(user);  
				  p.setCode(ResultCode.OK.getValue());
				  p.setMsg(ResultCode.OK.getName());
				  logger.info("新增用户成功");
				  return JSON.toJSONString(p);
			  }catch(Exception e){
					p.setCode(ResultCode.ERRO.getValue());
					p.setMsg(ResultCode.ERRO.getName());
					logger.info("异常信息："+e.getMessage());
					return JSON.toJSONString(p);
			  }
		  }else{
				p.setCode(ResultCode.NOTLOGIN.getValue());
				p.setMsg(ResultCode.NOTLOGIN.getName());
				logger.info("新增用户  -- 用户未登录");
				return JSON.toJSONString(p);
		  }
	}
	
	/**
	 * 5、删除用户
	 */
	public String delUserJson(String ids){
		PageJson pageJson=new PageJson();
		try {
			   userDao.delete(ids);
			   pageJson.setMsg("成功");
		} catch (Exception exception) {
			// TODO: handle exception
			pageJson.setCode(111111);
			pageJson.setMsg(exception.getMessage());
		}
		 logger.info(JSON.toJSONString(pageJson));
		return  JSON.toJSONString(pageJson);
	}
	
	/**
	 * 用户分页json字符串
	 * @return
	 */
	public String getUserJson(UserVO u){
		PageJson pageJson=new PageJson();
		List<User> ulist=new ArrayList<User>();
		try {
			   ulist=  userDao.queryUserList(u.getName(), u.getPage()-1,u.getLimit());
			   pageJson.setMsg("成功");
			   pageJson.setData(ulist);
			   pageJson.setCount(userDao.queryTotal(u.getName()));
		} catch (Exception exception) {
			// TODO: handle exception
			pageJson.setCode(111111);
			pageJson.setMsg(exception.getMessage());
		}
		
		 logger.info(JSON.toJSONString(pageJson));
		return  JSON.toJSONString(pageJson);
	}
	
	
	/**
	 * 查询User的全部数据
	 */
	public List<User> findAll() {
		PageJson pageJson=new PageJson();
		try {
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		List<User> findAllList = userDao.findAll();
		return findAllList;
	}

	/**
	 * 根据 id 查询 对应数据
	 */
	public User findById(String id) {
		User user=new User();
		try {
			 user = userDao.findById(id);
		} catch (Exception e) {
			
		}
		
		return user;
	}

	/**
	 * 新增数据
	 */
	public void save(User user) {
		user.setId(UUID.randomUUID().toString());
		userDao.insertSelective(user);
	}



	@Override
	public User login(String name, String pwd) {
		return userDao.login(name, pwd);
	}

	@Override
	public void updatePassword(User user) {
		if (user == null || StringUtils.isBlank(user.getId())) {
			return;
		}

		userDao.update(user);
	}

	@Override
	public List<User> queryUserList(String userName, int pageNo, int pageSize) {
		return userDao.queryUserList(userName, (pageNo - 1) * pageSize, pageSize);
	}

	@Override
	public int queryTotal(String userName) {
		return userDao.queryTotal(userName);
	}

	@Override
	public int queryUserName(String userName) {
		return userDao.queryUserName(userName);
	}

	
}
